package com.upf1sh.controller;
//import com.upf1sh.shop.ShopApplication;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.upf1sh.bean.User;
import com.upf1sh.mapper.UserMapper;
import com.upf1sh.service.UserService;
import com.upf1sh.utils.EmailCheck;
import com.upf1sh.utils.JwtUtils;
import com.upf1sh.utils.L_Code;
import com.upf1sh.utils.Result;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@CrossOrigin("*")
//@CrossOrigin(value = "http://116.204.81.67:8001", maxAge = 1800, allowedHeaders = "*")

public class UserController {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;
    //    private EmailCheck emailCheck;
    private String code = "1";
    //md5盐
    private String salt = "CauCX2030";

    public void setCode(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    @PostMapping("/login")
    // querystring: username=zhangsan&password=123   User user,String username,String password
    // json: {username:zhangsan,password:123}
    // 如果前端传递的数据是json格式，必须使用对象接收，同时需要添加@RequestBody
    public Result login(@RequestBody User user, HttpServletRequest request) throws UnsupportedEncodingException {
        User dbuser = userMapper.findByUN(user.getUsername());
        String ip;
/**
 * ip地址
 * 2023/4/27 20:52
 * UpF1sh
 */
        if (dbuser != null) {
            String pwd = user.getPassword();
            //md5密码加密
            String encodedPassword = DigestUtils.md5DigestAsHex((salt + salt + pwd + salt + salt).getBytes("UTF-8"));
            if (encodedPassword.equals(dbuser.getPassword())) {

                return Result.ok().data("tokenAndAuthority", userService.login(user, request));
            } else return Result.error().data("error", "密码错误！");
        }
        return Result.error().data("error", "请先注册！");
    }

    @PostMapping("/code")
    public void send(@RequestBody User user) throws EmailException {
        code = Integer.toString((int) (Math.random() * 1000000));
        System.out.println("code" + code);
        EmailCheck e = new EmailCheck();
        e.emailSend(user.getEmail(), code);
        this.setCode(code);
        setCode(code);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        User user1 = userMapper.findByUN(user.getUsername());
        if (user1 != null) return Result.error().data("error", "用户已存在!");
        else {
            code = this.getCode();
            if (code.equals(user.getEmailcode())) {
                user.setIsonline("1");
                int result = this.userMapper.insert(user);
                return Result.ok();
            } else return Result.error().data("error", "验证码错误！");
        }
    }

    @GetMapping("/info")  // "token:xxx"
    public Result info(String token) {
        String username = JwtUtils.getClaimsByToken(token).getSubject();
        User dbuser = userMapper.findByUN(username);
        String url = dbuser.getIcon();
        return Result.ok().data("name", username).data("avatar", url);
    }

    @PostMapping("/getUserById")
    public Result getUserById(int id) {
        User dbuser = userMapper.selectById(id);
        return Result.ok().data("user", dbuser);
    }

    @PostMapping("/getUserByName")
    public Result getUserByName(String name) {
        User dbuser = userMapper.findByUN(name);
        return Result.ok().data("user", dbuser);
    }

    @RequestMapping("/edit")
    public Result edit(User user) {
        // 根据userName修改
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", user.getId());
        int r = userMapper.update(user, updateWrapper);
        if (r == 1)
            return Result.ok();
        return Result.error();
    }

    @PostMapping("/logout")  // "token:xxx"
    public Result logout(String token) {
        String username = JwtUtils.getClaimsByToken(token).getSubject();
        System.out.println("logout" + username);
        userMapper.changeIsOnline("离线", username);
        L_Code.getMap().remove(username);
        return Result.ok();
    }


    @RequestMapping("/uploadicon")
//    @CrossOrigin(value = "http://116.204.124.80:8001", maxAge = 1800, allowedHeaders ="*")
    @CrossOrigin
    public String uploadicon(MultipartFile icon) {
        String originalFilename = icon.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString().replace("-", "") + originalFilename;

//        String dirPath = System.getProperty("user.dir");
        String dirPath = ("/data");
        String path = "/" + "icon" + "/" + newFileName;

        File destFile = new File(dirPath + path);

        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            icon.transferTo(destFile);
            return path;
        } catch (IOException e) {
            System.out.println(e);
            return null;
        }
    }

    /**
     * 查询管理员
     * UpF1sh
     * 2023/4/24 16:27
     *
     * @return
     */
    @RequestMapping("/getAdmin")
    public Result selectAdmin() {
        return Result.ok().data("adminList", userService.selectAdmin());
    }

    /**
     * 获得普通用户
     *
     * @return
     */
    @RequestMapping("/getOUser")
    public Result selectOUser() {
        return Result.ok().data("oUserList", userService.selectOUser());
    }

    /**
     * 获得在线用户
     * 2023/4/27 20:44
     * UpF1sh
     *
     * @return
     */
    @RequestMapping("/getOnlineUser")
    public Result selectOnlineUser() {
        return Result.ok().data("onlineList", userService.selectOnlineUser());
    }

    /**
     * delete user
     * UpF1sh
     * 2023/4/26 15:42
     */
    @RequestMapping("/deleteUser")
    public Result deleteUser(String username) {
        return userService.deleteUser(username) == 1 ? Result.ok().message("删除成功!") : Result.error().message("删除失败!");
//        if (userService.deleteUser(username) == 1)
//            return Result.ok().message("删除成功!");
//        return Result.error().message("删除失败!");
    }

    /**
     * delete admin
     * 2023/4/29 10:53
     *
     * @param username
     * @return
     */
    @RequestMapping("/deleteAdmin")
    public Result deleteAdmin(String username) {
        return userService.deleteUser(username) == 1 ? Result.ok().message("删除成功!") : Result.error().message("删除失败!");
//        if (userService.deleteUser(username) == 1)
//            return Result.ok().message("删除成功!");
//        return Result.error().message("删除失败!");
    }

    /**
     * delete user
     * UpF1sh
     * 2023/4/26 15:42
     */
    @RequestMapping("/addUser")
    public Result addUser(String username, String password, String phoneNumber, String email) throws UnsupportedEncodingException {

        int result = userService.addUser(username, password, phoneNumber, email);
        if (result == 1) {
            return Result.ok().data("success", "添加成功!");
        } else if (result == 0)
            return Result.error().data("error", "插入失败!");
        else return Result.error().data("error", "用户名已存在！添加失败");
    }

    /**
     * 管理员退出用户
     * 2023/4/27 21:47
     *
     * @param username
     * @return
     */
    @RequestMapping("/quitUser")
    public Result quitUser(String username) {
        String quit = "离线";
        return userService.quitUser(quit, username) == 1 ? Result.ok().data("success", "用户已成功下线！") : Result.error().data("error", "用户已离线，无需操作!");
    }

    @RequestMapping("/resetPassword")
    public Result resetPassword(String username, String password) throws UnsupportedEncodingException {
        //md5密码加密
        String encodedPassword = DigestUtils.md5DigestAsHex((salt + salt + password + salt + salt).getBytes("UTF-8"));

        return userMapper.resetPassword(username, encodedPassword) == 1 ? Result.ok().data("success", "修改成功！") : Result.error().data("error", "修改失败！");
    }

    @RequestMapping("/addAdmin")
    public Result addAdmin(String username, String password, String phoneNumber, String email) throws UnsupportedEncodingException {
        int result = userService.addAdmin(username, password, phoneNumber, email);
        if (result == 1) {
            return Result.ok().data("success", "添加成功!");
        } else if (result == 0)
            return Result.error().data("error", "插入失败!");
        else return Result.error().data("error", "用户名已存在！添加失败");
    }

}
